Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Namespace SerialPortProfileApplication

	Public Partial Class Form1
		Inherits Form
        Private devList As List(Of C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                                    Device) = Nothing
        Private serialService As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                                    RemoteService = Nothing
        Private networkStream As System.Net.Sockets.NetworkStream = Nothing
        Private actualDataRead() As Byte = Nothing
        Private actualDataWrite() As Byte = Nothing

        Public Sub New()
            InitializeComponent()
            btnProperties.Enabled = False
            btnConnect.Enabled = False
            btnStart.Enabled = False
            btnStop.Enabled = False
            cmbServices.Enabled = False
            cmbPortName.Enabled = False

            devList = deviceServicesManager1.DiscoverAllDevices()
            If devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                                        Device In devList

                    cmbDevice.Items.Add(dev.Name)
                Next

            End If

            If devList.Count > 0 Then

                cmbServices.Enabled = True
            End If

        End Sub

        Private Sub btnProperties_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnProperties.Click
            Try
                Dim portSettingdForm As New PortSettings(Me.sppManager1)
                portSettingdForm.ShowDialog()

            Catch ex As Exception
                Microsoft.VisualBasic.MsgBox("Unable to set the properties for port. " & cmbPortName. _
                                            Text & "." & ex.Message, Microsoft.VisualBasic.MsgBoxStyle.Critical _
                                             Or Microsoft.VisualBasic.MsgBoxStyle.OkOnly, "Serial Port Application")

            End Try

        End Sub

        Private Sub btnExit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click
            If sppManager1 IsNot Nothing Then

                If sppManager1.IsPortOpen Then
                    sppManager1.ClosePort()
                End If

            End If

            Dispose()

        End Sub

        Private Sub btnStart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnStart.Click
            Try
                If Not String.IsNullOrEmpty(cmbPortName.Text) AndAlso networkStream _
                                                                       IsNot Nothing Then

                    sppManager1.NetworkStream = Me.networkStream

                    ' Open port.
                    sppManager1.OpenPort()
                    btnStart.Enabled = False
                    btnStop.Enabled = True
                    cmbPortName.Enabled = False
                Else

                    Microsoft.VisualBasic.MsgBox("Please enter a valid Port name for e.g. COM1", _
                                                    Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                                 Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                                 "Serial Port Application")
                    cmbPortName.Focus()
                End If

            Catch ex As Exception
                Dim errMessage As String = ""
                If ex.InnerException IsNot Nothing Then
                    errMessage = ex.Message & ex.InnerException.Message
                Else
                    errMessage = ex.Message
                End If

                Microsoft.VisualBasic.MsgBox("Unable to start service." & errMessage, _
                                                Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
                btnStart.Enabled = True
                btnStop.Enabled = False
                cmbPortName.Enabled = True
            End Try

        End Sub

        ' Data from remote service.
        Private Sub serialPortManager_DataDetectedFromRemoteDevice(ByVal sender As Object, _
                                                                    ByVal e As EventArgs) Handles sppManager1.DataDetectedFromRemoteDevice
            Try
                Dim bData() As Byte = {}
                Dim numRead As Integer = sppManager1.SendDataToSerialPort(bData)
                actualDataRead = New Byte(numRead - 1) {}
                Array.Copy(bData, actualDataRead, numRead)
                Me.Invoke(New EventHandler(AddressOf DisplayDataReceivedFromRemoteService))

            Catch ex As Exception
                Microsoft.VisualBasic.MsgBox("Unexpected error while reading data sent by Remote Service for Legacy Application." _
                                         & ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
            End Try

        End Sub

        ' Data from Legacy Application
        Private Sub serialPortManager_DataDetectedOnSerialPort(ByVal sender As Object, _
                                                                ByVal e As EventArgs) Handles sppManager1.DataDetectedOnSerialPort
            Try
                Dim bData() As Byte = {}
                Dim numRead As Integer = sppManager1.SendDataToRemoteDevice(bData)
                actualDataWrite = New Byte(numRead - 1) {}
                Array.Copy(bData, actualDataWrite, numRead)
                Me.Invoke(New EventHandler(AddressOf DisplayDataReceivedFromSerialPort))

            Catch ex As Exception
                Microsoft.VisualBasic.MsgBox("Unexpected error while reading data sent by Legacy application for Remote Service." _
                                         & ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
            End Try

        End Sub

        Private Sub btnDiscover_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDiscover.Click
            cmbDevice.Items.Clear()
            cmbServices.Items.Clear()
            cmbDevice.Text = ""
            cmbServices.Text = ""
            cmbServices.Enabled = False
            btnConnect.Enabled = False
            Me.Cursor = Cursors.WaitCursor
            devList = deviceServicesManager1.DiscoverAllDevices()
            If devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                                        Device In devList
                    cmbDevice.Items.Add(dev.Name)
                Next

            End If

            If devList.Count > 0 Then

                cmbServices.Enabled = True
            End If

            Me.Cursor = Cursors.Default
        End Sub

        Private Sub cmbServices_Enter(ByVal sender As Object, ByVal e As EventArgs) Handles cmbServices.Enter
            cmbServices.Items.Clear()
            If devList IsNot Nothing AndAlso devList.Count <> 0 Then
                For Each dev As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                                        Device In devList
                    If dev.Name = cmbDevice.Text.ToString() Then
                        Dim serialServiceList As List(Of C4F.DevKit.Bluetooth. _
                        ServiceAndDeviceDiscovery.RemoteService) = deviceServicesManager1. _
                                                                DiscoverServicesByType(dev, _
                                                              C4F.DevKit.Bluetooth. _
                                                               ServiceAndDeviceDiscovery. _
                                                              ServiceType.SerialPortProfile)

                        If serialServiceList IsNot Nothing AndAlso _
                                                        serialServiceList.Count <> 0 Then
                            For Each remServ As C4F.DevKit.Bluetooth. _
                                                          ServiceAndDeviceDiscovery. _
                                                          RemoteService In _
                                                          serialServiceList
                                serialService = remServ
                                cmbServices.Items.Add(remServ.Name)
                            Next

                        End If

                    End If

                Next

            End If
            If cmbServices.Items.Count > 0 Then
                btnConnect.Enabled = True
            End If

        End Sub

        Private Sub btnConnect_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConnect.Click
            Try

                Me.Cursor = Cursors.WaitCursor
                If serialService IsNot Nothing Then
                    networkStream = serialService.Connect()
                    btnConnect.Enabled = False
                    cmbServices.Enabled = False
                    btnProperties.Enabled = True
                    cmbPortName.Enabled = True
                    btnStart.Enabled = True
                End If

            Catch servEx As C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery. _
                                                            ServiceConnectionException
                btnConnect.Enabled = True
                cmbServices.Enabled = True
                btnProperties.Enabled = False
                cmbPortName.Enabled = False
                btnStart.Enabled = False
                Microsoft.VisualBasic.MsgBox(servEx.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
            End Try

            Me.Cursor = Cursors.Default
        End Sub

        Private Sub btnStop_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnStop.Click
            Try

                If sppManager1.IsPortOpen Then
                    sppManager1.ClosePort()
                End If

                btnStop.Enabled = False
                btnStart.Enabled = True
                cmbDevice.Enabled = True
                cmbPortName.Enabled = True

            Catch ex As Exception
                If ex.InnerException Is Nothing Then
                    Microsoft.VisualBasic.MsgBox(ex.Message, Microsoft.VisualBasic.MsgBoxStyle.Critical _
                                                 Or Microsoft.VisualBasic.MsgBoxStyle.OkOnly, "Serial Port Application")

                Else
                    Microsoft.VisualBasic.MsgBox(ex.Message & ex.InnerException.Message, Microsoft.VisualBasic.MsgBoxStyle.Critical _
                                                 Or Microsoft.VisualBasic.MsgBoxStyle.OkOnly, _
                                                    "Serial Port Application")

                End If
            End Try

        End Sub


        ' Data from normal service.
        Public Sub DisplayDataReceivedFromSerialPort(ByVal sender As Object, _
                                                      ByVal e As EventArgs)
            If actualDataWrite IsNot Nothing Then
                txtBoxLegacyApp.Text &= "> " & Encoding.ASCII.GetString(actualDataWrite). _
                                                            Trim() & Environment.NewLine
                actualDataWrite = Nothing
            End If

        End Sub

        ' Data from remote service.
        Public Sub DisplayDataReceivedFromRemoteService(ByVal sender As Object, _
                                                         ByVal e As EventArgs)
            If actualDataRead IsNot Nothing Then
                txtBoxRemoteServ.Text &= "> " & Encoding.ASCII.GetString(actualDataRead). _
                                                            Trim() & Environment.NewLine
                actualDataRead = Nothing
            End If

        End Sub

        Private Sub cmbPortName_SelectedIndexChanged(ByVal sender As Object, _
                                                      ByVal e As EventArgs) Handles cmbPortName.SelectedIndexChanged

            If String.IsNullOrEmpty(cmbPortName.Text) Then
                btnProperties.Enabled = False
            Else
                btnProperties.Enabled = True
            End If

            Try

                sppManager1.PortName = cmbPortName.Text

            Catch ex As Exception
                If ex.InnerException Is Nothing Then
                    Microsoft.VisualBasic.MsgBox(ex.Message, Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
                Else
                    Microsoft.VisualBasic.MsgBox(ex.Message & ex.InnerException.Message, _
                                                 Microsoft.VisualBasic.MsgBoxStyle.OkOnly Or _
                                             Microsoft.VisualBasic.MsgBoxStyle.Critical, _
                                             "Serial Port Application")
                End If

            End Try

        End Sub

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim portNames() As String = System.IO.Ports.SerialPort.GetPortNames()
            For Each port As String In portNames

                If Not cmbPortName.Items.Contains(port) Then
                    cmbPortName.Items.Add(port)
                End If

            Next

        End Sub

    End Class

End Namespace
